package com.yitong.Estshopping.controller;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.mobile.device.Device;
import org.springframework.mobile.device.DeviceUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yitong.Estshopping.entity.CategorySecond;
import com.yitong.Estshopping.entity.Categorys;
import com.yitong.Estshopping.entity.Image;
import com.yitong.Estshopping.entity.Product;
import com.yitong.Estshopping.entity.User;
import com.yitong.Estshopping.service.CategorySecondService;
import com.yitong.Estshopping.service.CategorysService;
import com.yitong.Estshopping.service.ImageService;
import com.yitong.Estshopping.service.ProductService;

/**
 * 商城首页
 * @author YT
 *
 */

@Controller
public class PageProductController {
	@Autowired
	private ProductService productService;
	
	@Autowired
	private CategorysService categorysService;
	@Autowired
	private CategorySecondService categorySecondService;
	@Autowired
	private ImageService imageService;
	/**
	 * 商品详情页面
	 * @param model
	 * @param pid
	 * @return
	 */
	@RequestMapping(value="/Productinfo/{pid}")
	public String listProduct(HttpServletRequest request,HttpSession session,Model model,@PathVariable Integer pid){
		String html = "product/info";
		String nohtml = "product/infonull";
		Device device = DeviceUtils.getCurrentDevice(request);
		if (device.isMobile()) {
			html="mobile/pinfo";
			nohtml="mobile/pnoinfo";
		}
		
		Product product = productService.getProduct(pid);
		if(ObjectUtils.isEmpty(product))return nohtml;
		System.out.println("该商品的状态"+product.getIsState());
		User user = (User) session.getAttribute("user");
		User user2 = product.getUser();
		if(!ObjectUtils.isEmpty(user)) {
			if(user.getUid()==user2.getUid()) {
				model.addAttribute("product",product);
				return html;
			}
		}
		if(product.getIsState().equals("on")) {
			
			//查询用户所有商品数量
			Integer count=productService.getcount(user2.getUid());
			model.addAttribute("count",count);
			//查询访问量
			Integer sumnub=productService.sumnub(user2.getUid());
			model.addAttribute("sumnub",sumnub);
			//查询用户最近发布的
			List<Product> getuserProductList = productService.getuserProductList(user2.getUid());
			model.addAttribute("userProduct",getuserProductList);
			
			if(product!=null) {
				//累加访问量
				productService.updateProductPnub(pid, 1);
				String json = JSONObject.toJSONString(product);
				model.addAttribute("product",product);
				model.addAttribute("productstring",json);
				
				return html;
			}else {
				return nohtml;
			}
		}else {
			return nohtml;
		}
		
	}
	@RequestMapping(value= {"/userinfo/ProductSet"})
	public String ProductAdd(HttpSession session ,Model model){
		List<Categorys> findAll = categorysService.findAll();
		model.addAttribute("Categorys", findAll);
			return "user/productSet";
	}
	@RequestMapping(value= "/userinfo/ProductSet/{pid}")
	public String ProductSet(HttpSession session ,Model model,@PathVariable(value="pid") Integer pid){
		User user = (User) session.getAttribute("user");
		Product product = productService.getProduct(pid);
		if(product==null) {
			return "user/nofind";
		}
		User user2 = product.getUser();
		if(user.getKey().equals(user2.getKey())) {
			List<Categorys> findAll = categorysService.findAll();
			model.addAttribute("Categorys", findAll);
			model.addAttribute("product", product);
			return "user/productSet";
		}else {
			return "user/nofind";
		}
	}
	/**
	 * 保存商品
	 */
	@RequestMapping(value = "/userinfo/addProductlist/{csid}", method = RequestMethod.POST,produces = "application/json;charset=utf-8")
	public @ResponseBody Map<String,Object> addProductlist(HttpSession session,@RequestBody Product product,@PathVariable Integer csid) {
		//public @ResponseBody Map<String,Object> addProductlist(HttpSession session,@RequestBody  String pram) {
		
		Map<String,Object> map = new HashMap<String,Object>();
		//二级类目
		CategorySecond categorySecond = categorySecondService.findCategorySecond(csid);
		product.setCategorySecond(categorySecond);
		User user = (User) session.getAttribute("user");
		product.setUser(user);
		Date date = new Date();
		product.setPdate(date); 
		product.setIsState("on");
		Product prId=null;
		if(product.getPid()==null) {
			productService.saveProduct(product);
			prId = productService.getPrId(date);
		}
		//关联图片
		prId = productService.getProduct(product.getPid());
		//查询被关联的图片
		List<Image> images = imageService.getPid(prId.pid);
		if(images.size()>0) {
			for (Image image : images) {
				//解除关联商品
				imageService.updateImgid(image.getImgid(), null);
			}
		}
		System.out.println(csid);
		System.out.println(product.getPname());
		String imgsrcs = product.getImgsrcs();
		System.out.println(imgsrcs);
		JSONArray parseArray = JSONObject.parseArray("["+imgsrcs+"]");
		/*String array[]=new String[((CharSequence) imgsrcs).length()];
		imgsrcs = imgsrcs.replace("{", "[{");
		imgsrcs = imgsrcs.replace("]", "");
		imgsrcs = imgsrcs.replace("\"", "");
		String split[] = ((String) imgsrcs).split(",");
		product.setImgsrcs(imgsrcs);*/
		productService.updateProduct(product);
		Image image = new Image();
		for (Object o : parseArray) {
			String string = o.toString();
			System.out.println(string);
			@SuppressWarnings("unchecked")
			Map<String, Object> map2 =(Map<String, Object>) o;
			for (String s : map2.keySet()) {  
			   System.out.println("key=" + s + " value=" + map2.get(s));  
			  }  
			image.setColor(map2.get("color").toString());
			image.setUser(user);
			image.setProduct(product);
			image.setUname(map2.get("uname").toString());
			image.setSrc(map2.get("src").toString());
			image.setTitle(product.getPname().toString());
			String h = map2.get("height").toString();
			System.out.println("图片高度"+h);
			image.setHeight(Integer.parseInt(h));
			String w = map2.get("width").toString();
			image.setWidth(Integer.parseInt(w));
			
			imageService.save(image);
		}
		//图片关联pid
		/*for (String string : split) {
			System.out.println(string);
			JSONObject parseObject = JSONObject.parseObject(string);   
			System.out.println("图片地址-----"+parseObject.toJSONString());
		}*/
		/**
		 * 图片重写商品里
		 */
		System.out.println("保存后商品ID"+product.getPid());
		System.out.println("保存后商品ID"+prId.getPid());
		map.put("flag", true);
	    map.put("rest", "添加成功");
		return map;
	}
	@RequestMapping(value = "/userinfo/pdelete/{pid}", method = RequestMethod.POST,produces = "application/json;charset=utf-8")
	public @ResponseBody Map<String,Object> delProduct(HttpSession session,@PathVariable("pid") Integer pid){
		Map<String,Object> map = new HashMap<String,Object>();
		User user = (User) session.getAttribute("user");
		Product product = productService.getProduct(pid);
		if(product==null) {
			map.put("msg", "你很皮,该商品不是你的商品");
		}else {
			List<Image> images = imageService.getPid(pid);
			if(images.size()>0) {
				for (Image image : images) {
					imageService.delete(image);
				}
			}
			productService.deleteProduct(product);
			map.put("msg", "删除成功");
		}
		return map;
		
	}
	/**
	 * 一级目录查询
	 * @param model
	 * @param cid
	 * @return
	 */
	@RequestMapping(value="/classify/{cid}",method=RequestMethod.GET)
	public String listclassify(
			HttpServletRequest request,
			HttpSession session,
			HttpServletResponse response,
			Model model,@PathVariable Integer cid,@RequestParam(required=false) Integer page,@RequestParam(required=false) Integer limit){
		String cname = categorysService.findCategory(cid).getCname();
		if(page==null) {
			page=1;
		}
		if(limit==null) {
			limit=12;
		}
		System.out.println("页码"+page);
		List<Product>  products=  productService.getProductListone(cid,page,limit);
		//展现随机商品
		if(products.size()==0) {
			List<Product> productssuiji=productService.getProductListRAND();
			model.addAttribute("productssuiji",productssuiji);
		}
		model.addAttribute("products",products);
		model.addAttribute("count",productService.countProductone(cid));
		model.addAttribute("limit", limit);
		model.addAttribute("title", cname);
		model.addAttribute("page", page);
		//model.addAttribute("url", request.getRequestURI());
		Device device = DeviceUtils.getCurrentDevice(request);
		if (device.isMobile()) {
			return "mobile/listm";
		}
    	return "product/list1";
	}
	/**
	 * 查询二级目录商品
	 * @param model
	 * @param cid
	 * @param page
	 * @return
	 */
	@RequestMapping(value="/classify2/{csid}")
	public String listclassify2(
			HttpServletRequest request,
			HttpSession session,
			HttpServletResponse response,
			Model model,@PathVariable Integer csid,@RequestParam(required=false) Integer page,@RequestParam(required=false) Integer limit){
		String csName = categorySecondService.findCategorySecond(csid).getCsName();
		if(page==null) {
			page=1;
		}
		if(limit==null) {
			limit=12;
		}
		List<Product>  products=  productService.getProductListcid(csid,page,limit);
		//展现随机商品
		if(products.size()==0) {
			List<Product> productssuiji=productService.getProductListRAND();
			model.addAttribute("productssuiji",productssuiji);
		}
		model.addAttribute("products", products);
		model.addAttribute("page", page);
		model.addAttribute("limit", limit);
		model.addAttribute("title", csName);
		model.addAttribute("count", productService.countProduct(csid));
		Device device = DeviceUtils.getCurrentDevice(request);
		if (device.isMobile()) {
			return "mobile/listm";
		}
    	return "product/list1";
	}
	/**
	 * 查询二级目录商品
	 * @param model
	 * @param cid
	 * @param page
	 * @return
	 */
	@RequestMapping(value="/zuixin")
	public String listzuixin(
			HttpServletRequest request,
			HttpSession session,
			HttpServletResponse response,
			Model model,@RequestParam(required=false) Integer page,@RequestParam(required=false) Integer limit){
		
		if(page==null) {
			page=1;
		}
		if(limit==null) {
			limit=12;
		}
		List<Product>  products=  productService.getProductdate(page, limit);
		model.addAttribute("products", products);
		model.addAttribute("page", page);
		model.addAttribute("limit", limit);
		model.addAttribute("title", "最新商品");
		model.addAttribute("count", productService.countProductdate());
		Device device = DeviceUtils.getCurrentDevice(request);
		if (device.isMobile()) {
			return "mobile/listm";
		}
    	return "product/list1";
	}
	/**
	 * 访问量最高的
	 * @param model
	 * @param cid
	 * @param page
	 * @return
	 */
	@RequestMapping(value="/zuigao")
	public String listzuigao(
			HttpServletRequest request,
			HttpSession session,
			HttpServletResponse response,
			Model model,@RequestParam(required=false) Integer page,@RequestParam(required=false) Integer limit){
		if(page==null) {
			page=1;
		}
		if(limit==null) {
			limit=12;
		}
		List<Product>  products=  productService.getProductPnub(page, limit);
		model.addAttribute("products", products);
		model.addAttribute("page", page);
		model.addAttribute("limit", limit);
		model.addAttribute("title", "大家都在看");
		model.addAttribute("count", productService.countProductdate());
		Device device = DeviceUtils.getCurrentDevice(request);
		if (device.isMobile()) {
			return "mobile/listm";
		}
    	return "product/list1";
	}
	/**
	 * 热门商品
	 * @param model
	 * @param cid
	 * @param page
	 * @return
	 */
	@RequestMapping(value="/remen")
	public String listremen(
			HttpServletRequest request,
			HttpSession session,
			HttpServletResponse response,
			Model model,
			@RequestParam(required=false) Integer page,
			@RequestParam(required=false) Integer limit){
		if(page==null) {
			page=1;
		}
		if(limit==null) {
			limit=12;
		}
		List<Product>  products=  productService.getProductPremen(page, limit);
		model.addAttribute("products", products);
		model.addAttribute("page", page);
		model.addAttribute("limit", limit);
		model.addAttribute("title", "热门商品");
		model.addAttribute("count", productService.countProductdatePremen());
		Device device = DeviceUtils.getCurrentDevice(request);
		if (device.isMobile()) {
			return "mobile/listm";
		}
    	return "product/list1";
	}
	/**
	 * 输入字模糊搜索提示
	 * @param key
	 * @param page
	 * @param limit
	 * @param request
	 * @param session
	 * @param response
	 * @return
	 */
	@RequestMapping(value= "/searchmap")
	public  @ResponseBody Map<String,Object> findSearch(
			String key,
			Integer page, 
			Integer limit,
			HttpServletRequest request,
			HttpSession session,
			HttpServletResponse response){
		Map<String,Object> resultMap = new HashMap<String,Object>();
		if(page==null) {
			page=1;
		}
		if(limit==null) {
			limit=12;
		}
		
		List<Product>  products=  productService.listSearch(key,page,limit);
		
		ArrayList<Object> arrayList = new ArrayList<>();
		for (Product product : products) {
			arrayList.add(product.pname);
		}
		resultMap.put("k", arrayList);
		return resultMap;
	}
	/**
	 * 模糊搜索关键词
	 * @param key
	 * @param page
	 * @param limit
	 * @param request
	 * @param session
	 * @param response
	 * @return
	 */
	@RequestMapping(value= "/search/{key}")
	public  String listSearch(
			@PathVariable("key") String key,
			Integer page, 
			Integer limit,
			HttpServletRequest request,
			HttpSession session,
			HttpServletResponse response,
			Model model
			){
		if(page==null) {
			page=1;
		}
		if(limit==null) {
			limit=12;
		}
		Map<String,Object> resultMap = new HashMap<String,Object>();
		
		if(ObjectUtils.isEmpty(key)) {
			return "mobile/pnoinfo";
		}
		String letters = "(!@#$%^&*;':)";
		char c;
		for(int i = 0; i < key.length(); i ++ )
	     {
	          c = key.charAt( i );
	          
	   			if (letters.indexOf(c)>0){
	   				return "mobile/pnoinfo";
	   			}
	     }
		List<Product>  products=  productService.listSearch(key,page,limit);
		model.addAttribute("products", products);
		model.addAttribute("page", page);
		model.addAttribute("limit", limit);
		model.addAttribute("title", key);
		model.addAttribute("key", key);
		model.addAttribute("count", productService.listSearchcount(key));
		
		Device device = DeviceUtils.getCurrentDevice(request);
		if (device.isMobile()) {
			return "mobile/listm";
		}
    	return "product/list1";

	}
	
}
